<template>
  <div class="notification-center">
    <div class="operation-bar">
      <div class="header-actions">
        <div class="spacer"></div>
        <el-button 
          type="primary" 
          link 
          :disabled="!hasUnread"
          @click="handleMarkAllAsRead"
        >
          全部标为已读
        </el-button>
        <el-divider direction="vertical" />
        <el-button 
          type="danger" 
          link 
          :disabled="!notifications.length"
          @click="handleDeleteAll"
        >
          清空通知
        </el-button>
      </div>
    </div>

    <LoadingWrapper :loading="loading">
      <div>
        <el-tabs v-model="activeTab" v-if="notifications.length > 0">
          <el-tab-pane label="全部通知" name="all">
            <notification-list 
              :notifications="paginatedNotifications"
              @read="handleRead"
            />
          </el-tab-pane>
          <el-tab-pane label="未读通知" name="unread">
            <notification-list 
              :notifications="paginatedUnreadNotifications"
              @read="handleRead"
            />
          </el-tab-pane>
        </el-tabs>
        <el-empty v-else description="暂无通知" />
      </div>
    </LoadingWrapper>

    <div class="pagination-wrapper">
      <PaginationBar
        v-if="currentTabNotifications.length > 0"
        v-model:currentPage="currentPage"
        v-model:pageSize="pageSize"
        :total="currentTabNotifications.length"
        :pageSizes="[5, 10, 15, 20]"
        @pagination-change="handlePaginationChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import NotificationList from './NotificationList.vue'
import { getNotifications, markAsRead, markAllAsRead, deleteAllNotifications } from '@/api/notification'
import { formatDateTime } from '@/utils/format'
import PaginationBar from '@/components/pagination/PaginationBar.vue'
import LoadingWrapper from '@/components/loading/LoadingWrapper.vue'

const activeTab = ref('all')
const notifications = ref([])
const currentPage = ref(1)
const pageSize = ref(5)
const loading = ref(true)

const hasUnread = computed(() => 
  notifications.value.some(n => n.is_read === 0)
)

const unreadNotifications = computed(() => 
  notifications.value.filter(n => n.is_read === 0)
)

const currentTabNotifications = computed(() => {
  return activeTab.value === 'all' ? notifications.value : unreadNotifications.value
})

const paginatedNotifications = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return notifications.value.slice(start, end)
})

const paginatedUnreadNotifications = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value
  const end = start + pageSize.value
  return unreadNotifications.value.slice(start, end)
})

const handlePaginationChange = ({ type, value }) => {
  if (type === 'page') {
    currentPage.value = value
  } else if (type === 'size') {
    pageSize.value = value
    currentPage.value = 1
  }
}

watch(activeTab, () => {
  currentPage.value = 1
})

const loadNotifications = async () => {
  try {
    loading.value = true
    const response = await getNotifications()
    if (response.code === 200) {
      notifications.value = response.data.map(notification => ({
        ...notification,
        createTime: formatDateTime(notification.created_at)
      }))
    }
  } catch (error) {
    console.error('获取通知失败:', error)
    ElMessage.error('获取通知失败')
  } finally {
    loading.value = false
  }
}

const handleRead = async (notification) => {
  try {
    const response = await markAsRead(notification.id)
    if (response.code === 200) {
      notification.is_read = 1
      ElMessage.success('已读')
    }
  } catch (error) {
    ElMessage.error('操作失败，请稍后重试')
  }
}

const handleMarkAllAsRead = async () => {
  try {
    const response = await markAllAsRead()
    if (response.code === 200) {
      notifications.value.forEach(n => n.is_read = 1)
      ElMessage.success('已读全部通知')
      loadNotifications() 
    }
  } catch (error) {
    ElMessage.error('已读失败，请稍后重试')
  }
}

const handleDeleteAll = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有通知吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await deleteAllNotifications()
    if (response.code === 200) {
      notifications.value = []
      ElMessage.success('已清空所有通知')
    }
  } catch (error) {
    if (error === 'cancel') return
    ElMessage.error('清空通知失败，请稍后重试')
  }
}

onMounted(() => {
  loadNotifications()
})
</script>

<style scoped>
.notification-center {
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.empty-state {
  text-align: center;
  color: #909399;
  padding: 40px 0;
}

.header-actions {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 20px;
}

/* 占据剩余空间 使其靠右 */
.spacer {
  flex: 1;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.pagination-wrapper :deep(.el-pagination) {
  display: flex;
  justify-content: flex-end;
}
</style> 